package com.wbb.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wbb.mapper.TbTypeTemplateMapper;
import com.wbb.model.TbTypeTemplate;
import com.wbb.model.TbTypeTemplateExample;
import com.wbb.service.TemplateService;
import com.wbb.util.pageList;
import com.wbb.util.queryParams;
import com.wbb.vo.TypeTemplateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class TemplateServiceImpl implements TemplateService {
    @Autowired
    private TbTypeTemplateMapper templateMapper;

    @Override
    public pageList<TypeTemplateVo> queryPage(queryParams<TypeTemplateVo> params) {
        Page<TbTypeTemplate> page = PageHelper.startPage(params.getPageNum(), params.getPageSize());
        TbTypeTemplateExample templateExample = new TbTypeTemplateExample();
        if (params.getParams().getName() != null && !params.getParams().getName().isEmpty()){
            templateExample.createCriteria().andNameLike("%"+params.getParams().getName()+"%");
        }
        List<TbTypeTemplate> tbTypeTemplates = templateMapper.selectByExample(templateExample);
        PageInfo<TbTypeTemplate> pageInfo = page.toPageInfo();
        List<TbTypeTemplate> list = pageInfo.getList();
        List<TypeTemplateVo> collect = list.stream().map(type -> {
            TypeTemplateVo templateVo = new TypeTemplateVo();
            BeanUtils.copyProperties(type, templateVo);
            return templateVo;
        }).collect(Collectors.toList());
        return new pageList<>(pageInfo.getTotal(),collect);
    }

    @Override
    public void deleteById(Long id) {
        templateMapper.deleteByPrimaryKey(id);
    }

    @Override
    public TypeTemplateVo updateById(Long id) {
        TbTypeTemplate tbTypeTemplate = templateMapper.selectByPrimaryKey(id);
        TypeTemplateVo templateVo = new TypeTemplateVo();
        BeanUtils.copyProperties(tbTypeTemplate,templateVo);
        return templateVo;
    }

    @Override
    public void updateType(TypeTemplateVo templateVo) {
        TbTypeTemplate tbTypeTemplate = new TbTypeTemplate();
        BeanUtils.copyProperties(templateVo,tbTypeTemplate);
        templateMapper.updateByPrimaryKeySelective(tbTypeTemplate);
    }

    @Override
    public void addType(TypeTemplateVo templateVo) {
        TbTypeTemplate tbTypeTemplate = new TbTypeTemplate();
        BeanUtils.copyProperties(templateVo,tbTypeTemplate);
        templateMapper.insertSelective(tbTypeTemplate);
    }

    @Override
    public void batchType(List<Long> ids) {
        TbTypeTemplateExample templateExample = new TbTypeTemplateExample();
        templateExample.createCriteria().andIdIn(ids);
        templateMapper.deleteByExample(templateExample);
    }
}
